﻿using System;
using System.Windows.Forms;

namespace DitaImport
{
	/// <summary>
	/// Implements the UI that displays logging information.
	/// </summary>
	public partial class frmLog
	{
		#region Fields (2) 

		private int _percentComplete = 0;
		/// <summary>
		/// Specifies that the user canceled the current import
		/// </summary>
		public bool CancelImport = false;

		#endregion Fields 

		#region Constructors (1) 

		internal frmLog()
		{
			InitializeComponent();
		}

		#endregion Constructors 

		#region Methods (6) 

		// Public Methods (3) 

		/// <summary>
		/// Clears items from the logging information
		/// </summary>
		public void Clear()
		{
			listboxLog.Items.Clear();
			CancelImport = false;
		}

		/// <summary>
		/// Adds an item to the log
		/// </summary>
		/// <param name="e"></param>
		public void Log(LogEventArgs e)
		{
			listboxLog.Items.Add(e.Message);
			listboxLog.SelectedIndex = listboxLog.Items.Count - 1;
			listboxLog.TopIndex = listboxLog.Items.Count - 1;
			listboxLog.Refresh();
			if (e.Exception != null)
			{
				LogRecursiveException(e.Exception, 1);
			}
			Application.DoEvents();
		}

		/// <summary>
		/// Updates the UI with the current completion percentage for the import.
		/// </summary>
		/// <param name="Upto">Number of items processed</param>
		/// <param name="Max">Total number of items</param>
		/// <param name="Title">Name of current process.</param>
		public void UpdatePercentComplete(int Upto, int Max, string Title)
		{
			_percentComplete = Convert.ToInt32((Upto * 10000) / (Max * 100));
			this.Text = string.Format("{0} -- {1}% complete -- {2} / {3} files", Title, _percentComplete, Upto, Max);
		}
		// Private Methods (3) 

		/// <summary>
		/// Cancels the current process.
		/// </summary>
		/// <param name="sender">Object that initiated the event</param>
		/// <param name="e">Arguments for the event</param>
		private void btnCancel_Click(object sender, System.EventArgs e)
		{
			this.CancelImport = true;
		}

		private void btnOpenTxtFile_Click(object sender, System.EventArgs e)
		{
			string path = System.IO.Path.GetTempFileName() + ".txt";
			System.IO.StreamWriter filestream = new System.IO.StreamWriter(path, false);
			for (int i = 0; i < listboxLog.Items.Count; i++)
			{
				filestream.WriteLine(listboxLog.Items[i]);
			}
			filestream.Flush();
			filestream.Close();
			System.Diagnostics.Process.Start(path);
		}

		private void LogRecursiveException(Exception Ex, int RecursionLevel)
		{
			listboxLog.Items.Add(new String(' ', RecursionLevel) + "EXCEPTION: " + Ex.Message);
			if (Ex.InnerException != null)
			{
				LogRecursiveException(Ex.InnerException, RecursionLevel + 1);
			}
		}

		#endregion Methods 
	}
}